package com.achang.achangmall.search.service.impl;

import com.achang.achangmall.search.conf.ElasticsearchConfig;
import com.achang.achangmall.search.constant.ESConstant;
import com.achang.achangmall.search.service.ProductSaveService;
import com.achang.common.to.es.SkuEsModel;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/******
 @author 阿昌
 @create 2021-10-03 20:21
 *******
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //上架商品
    @Override
    public Boolean productStatusUp(List<SkuEsModel> esModels) throws IOException {
        //给es中建立索引
        //给es保存数据
        BulkRequest bulkRequest = new BulkRequest();
        esModels.forEach(item->{
            //构造保存请求
            IndexRequest indexRequest = new IndexRequest(ESConstant.PRODUCT_INDEX);
            String json = JSON.toJSONString(item);
            indexRequest.source(json, XContentType.JSON);
            indexRequest.id(item.getSkuId().toString());

            bulkRequest.add(indexRequest);
        });
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);

        //todo 批量错误
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架完成：【{}】",collect);

        return b;
    }

}
